package com.example.fund.sqlquery;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.fund.BaseActivity;
import com.example.fund.R;
import com.example.fund.fundstocks.MyHScrollView;
import com.example.fund.util.SqlQueryUtil;
import com.example.fund.util.StringUtil;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SqlQueryList extends BaseActivity {

	private LinearLayout root;
	private TextView txtHistorySql;
	private TextView txtSql;
	private TextView txtQuery;
	private Map<String,String> historySqlMap;
	//header
	private TextView txtColumn0;
	private TextView txtColumn1;
	private TextView txtColumn2;
	private TextView txtColumn3;
	private TextView txtColumn4;
	private TextView txtColumn5;
	private TextView txtColumn6;
	private TextView txtColumn7;
	private TextView txtColumn8;
	private TextView txtColumn9;


	//自定义弹出选择框
	private PopupWindow popupWindow;
	private ListView popupList;

	//当前点击的TextView
	private TextView tv;
	private TextView numberTv;

	//表格数据
	private List<SqlQueryInfo> dataList;

	private MyHScrollView headSrcrollView;
	private ListView mListView1;
	private MyAdapter myAdapter;
	private RelativeLayout mHead;


	private int bg1 = Color.rgb(5, 167, 247);
	private int bg2 = Color.rgb(233,244,251);

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
		setContentView(R.layout.sqlquerylist_dialog);

		root = (LinearLayout)findViewById(R.id.root);
    	root.setBackgroundColor(bg1);
    	LinearLayout layoutTop = (LinearLayout)findViewById(R.id.layoutTop);
    	layoutTop.setBackgroundColor(bg1);

		txtHistorySql = (TextView) findViewById(R.id.txtHistorySql);
		txtSql = (TextView) findViewById(R.id.txtSql);
    	txtQuery = (TextView) findViewById(R.id.txtQuery);

		txtColumn0 = (TextView) findViewById(R.id.txtColumn0);
		txtColumn1 = (TextView) findViewById(R.id.txtColumn1);
		txtColumn2 = (TextView) findViewById(R.id.txtColumn2);
		txtColumn3 = (TextView) findViewById(R.id.txtColumn3);
		txtColumn4 = (TextView) findViewById(R.id.txtColumn4);
		txtColumn5 = (TextView) findViewById(R.id.txtColumn5);
		txtColumn6 = (TextView) findViewById(R.id.txtColumn6);
		txtColumn7 = (TextView) findViewById(R.id.txtColumn7);
		txtColumn8 = (TextView) findViewById(R.id.txtColumn8);
		txtColumn9 = (TextView) findViewById(R.id.txtColumn9);
        //数据
		historySqlMap = SqlQueryUtil.getHistorySqlMap();
		dataList = new LinkedList<SqlQueryInfo>();
    	//初始化自定义下拉框
        View contentView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.popupwindow, null);
        contentView.setBackgroundColor(bg2);
        popupWindow = new PopupWindow(root, 1000, 900);
        popupWindow.setContentView(contentView);
        popupList = (ListView) contentView.findViewById(R.id.popupList);
        popupList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));

		mHead = (RelativeLayout) findViewById(R.id.head);
		mHead.setFocusable(true);
		mHead.setClickable(true);
		mHead.setBackgroundColor(Color.parseColor("#b2d235"));
		mHead.setOnTouchListener(new ListViewAndHeadViewTouchLinstener());

		mListView1 = (ListView) findViewById(R.id.listView1);
		mListView1.setOnTouchListener(new ListViewAndHeadViewTouchLinstener());

		headSrcrollView = (MyHScrollView) mHead.findViewById(R.id.horizontalScrollView1);

		initData();
		initListener();
		txtQuery_OnClickListener();
//		mListView1.setSelection(selection);
	}


	/**
	 * 初始化数据
	 */
	private void initData() {
		if(historySqlMap!=null && historySqlMap.size()>0)
		{
			txtSql.setText(historySqlMap.get("最近执行的查询sql"));
		}
	}

	/**
	 * 注册事件
	 */
	private void initListener() {
		//历史sql点击弹出下拉框
		txtHistorySql.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0)
			{
				initPopWindow(txtHistorySql,historySqlMap.keySet().toArray());
			}
		});

    	//下拉框选中事件
    	popupList.setOnItemClickListener(new OnItemClickListener()
    	{
    		@Override
    		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
    		{
    			String text = ((TextView)arg1).getText().toString();
				txtSql.setText(historySqlMap.get(text));
    			popupWindow.dismiss();
    		}
    	});

    	//查询按钮点击事件
    	txtQuery.setOnClickListener(new OnClickListener()
    	{
    		@Override
    		public void onClick(View arg0)
    		{
    			txtQuery_OnClickListener();
    		}
    	});
	}

	/**
	 * 查询事件
	 * @param
	 */
	protected void txtQuery_OnClickListener() {
		String sqls = txtSql.getText().toString();
		dataList = SqlQueryUtil.getSqlQueryInfoList(sqls);

		if (dataList!=null && dataList.size()>0)
		{
			SqlQueryInfo info = dataList.get(0);
			txtColumn0.setText(StringUtil.dealNull(info.getColumnName0()));
			txtColumn1.setText(StringUtil.dealNull(info.getColumnName1()));
			txtColumn2.setText(StringUtil.dealNull(info.getColumnName2()));
			txtColumn3.setText(StringUtil.dealNull(info.getColumnName3()));
			txtColumn4.setText(StringUtil.dealNull(info.getColumnName4()));
			txtColumn5.setText(StringUtil.dealNull(info.getColumnName5()));
			txtColumn6.setText(StringUtil.dealNull(info.getColumnName6()));
			txtColumn7.setText(StringUtil.dealNull(info.getColumnName7()));
			txtColumn8.setText(StringUtil.dealNull(info.getColumnName8()));
			txtColumn9.setText(StringUtil.dealNull(info.getColumnName9()));
		}

		myAdapter = new MyAdapter(this, R.layout.sqlquerylist_header,dataList,headSrcrollView);
		mListView1.setAdapter(myAdapter);

		String sqlUp = sqls.toUpperCase().trim();
		if (sqlUp.startsWith("SELECT"))
		{
			historySqlMap.put("最近执行的查询sql",sqls);
		}
	}

    /**
     * 设置返回值
     */
    private void setResult()
    {
    	Intent dataContext = this.getIntent();
    	setResult(20, dataContext);
    }

    /**
     * 初始化弹出下拉框，
     * 适用范围：时间区间、涨幅、跌幅
     * @param view
     * @param objects
     */
	@SuppressWarnings("unchecked")
	private void initPopWindow(TextView view,final Object[] objects){
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, objects)
        {
        	@Override
        	public View getView(int position, View convertView, ViewGroup parent) {
        		TextView mTextView = new TextView(getApplicationContext());
                mTextView.setText(objects[position].toString());
                mTextView.setTextSize(15);
                mTextView.setTextColor(bg1);
                mTextView.setPadding(30, 10, 0, 10);
        		return mTextView;
        	}
        };
        popupList.setAdapter(adapter);
        popupWindow.showAsDropDown(view);
        tv = view;
    }

    @Override
    protected void onResume()
    {
    	if(getRequestedOrientation()!=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)//横屏
    	{
   // 		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    	}
    	super.onResume();
    }


	class ListViewAndHeadViewTouchLinstener implements View.OnTouchListener {

		@Override
		public boolean onTouch(View arg0, MotionEvent arg1) {
			//当在列头 和 listView控件上touch时，将这个touch的事件分发给 ScrollView
			headSrcrollView.onTouchEvent(arg1);
			return false;
		}
	}

	public class MyAdapter extends BaseAdapter {
		private List<HorizontalScrollView> mList = new ArrayList<HorizontalScrollView>();
        private List<SqlQueryInfo> list;
		private int id_row_layout;
		private LayoutInflater mInflater;
		private ViewHolder holder = null;

		public MyAdapter(Context context, int id_row_layout,List<SqlQueryInfo> list,MyHScrollView headSrcrollView) {
			super();
            this.list = list;
			this.id_row_layout = id_row_layout;
			mInflater = LayoutInflater.from(context);
			mList.add(headSrcrollView);
			headSrcrollView.setOnScrollChangedListener(mList);
		}

		@Override
		public int getCount() {
            int ret = 0;
            if(list!=null){
                ret = Math.min(100,list.size());
            }
            return ret;
		}

		@Override
		public Object getItem(int position) {
            return list.get(position);
		}

		@Override
		public long getItemId(int position) {
            return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parentView) {
        	final SqlQueryInfo info = (SqlQueryInfo) this.getItem(position);
            final int position1 = position;
			if (convertView == null) {
				synchronized (SqlQueryList.this) {
					convertView = mInflater.inflate(id_row_layout, null);
					holder = new ViewHolder();

					MyHScrollView scrollView1 = (MyHScrollView) convertView.findViewById(R.id.horizontalScrollView1);

					holder.scrollView = scrollView1;
					holder.txtColumn0 = (TextView) convertView.findViewById(R.id.txtColumn0);
					holder.txtColumn1 = (TextView) convertView.findViewById(R.id.txtColumn1);
					holder.txtColumn2 = (TextView) convertView.findViewById(R.id.txtColumn2);
					holder.txtColumn3 = (TextView) convertView.findViewById(R.id.txtColumn3);
					holder.txtColumn4 = (TextView) convertView.findViewById(R.id.txtColumn4);
					holder.txtColumn5 = (TextView) convertView.findViewById(R.id.txtColumn5);
					holder.txtColumn6 = (TextView) convertView.findViewById(R.id.txtColumn6);
					holder.txtColumn7 = (TextView) convertView.findViewById(R.id.txtColumn7);
					holder.txtColumn8 = (TextView) convertView.findViewById(R.id.txtColumn8);
					holder.txtColumn9 = (TextView) convertView.findViewById(R.id.txtColumn9);

					mList.add(scrollView1);
					scrollView1.setOnScrollChangedListener(mList);
					convertView.setTag(holder);
				}
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.txtColumn0.setText(StringUtil.dealNull(info.getColumn0()));
			holder.txtColumn1.setText(StringUtil.dealNull(info.getColumn1()));
			holder.txtColumn2.setText(StringUtil.dealNull(info.getColumn2()));
			holder.txtColumn3.setText(StringUtil.dealNull(info.getColumn3()));
			holder.txtColumn4.setText(StringUtil.dealNull(info.getColumn4()));
			holder.txtColumn5.setText(StringUtil.dealNull(info.getColumn5()));
			holder.txtColumn6.setText(StringUtil.dealNull(info.getColumn6()));
			holder.txtColumn7.setText(StringUtil.dealNull(info.getColumn7()));
			holder.txtColumn8.setText(StringUtil.dealNull(info.getColumn8()));
			holder.txtColumn9.setText(StringUtil.dealNull(info.getColumn9()));

			return convertView;
		}

		class ViewHolder {
			TextView txtColumn0;
			TextView txtColumn1;
			TextView txtColumn2;
			TextView txtColumn3;
			TextView txtColumn4;
			TextView txtColumn5;
			TextView txtColumn6;
			TextView txtColumn7;
			TextView txtColumn8;
			TextView txtColumn9;
			
			HorizontalScrollView scrollView;
		}
	}// end class my

	

}